<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>FileReader 图片视频上传 预览格式为Blob </title>
		<style type="text/css">
			.imgshow {
				padding: 2px;
				border: 2px antiquewhite;
				transition: background 1s;
				-moz-transition: background 1s;
				-webkit-transition: background 1s;
				-o-transition: background 1s;
			}

			.imgshow:hover {
				background: rgba(0, 0, 0, 0.2);
			}

			input[type=file] {
				top: 0;
				left: 0;
				width: 100px;
				height: 100px;
				overflow: hidden;
				/* cursor: pointer; */
				/*设置input不显示*/
				/* opacity: 0; */
				background: url(../img/24.png) round;
				background:  -webkit-url(../img/24.png) round;
				cursor: pointer;
				/* 上面的代码是常规设置， 即：引入一个图片背景，设置在中心位置，大小和按钮的大小一致，以及鼠标指针为手型 */
				/*设置背景图片大小*/
				background-size: 100%;
				display: block;
				font-size: 0;
				line-height: 0;
				text-indent: -9999px;
			}

			input[type=file]:active {
				border: white;
			}

			.imgcontshow {
				visibility: hidden;
				opacity: 0;
				transform: scaleY(0);
				transition: .3s;
				animation: show .5s forwards;
			}

			@keyframes show {
				0% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(0)
				}

				40% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(1)
				}

				60% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(0)
				}

				80% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(2)
				}

				100% {
					visibility: visible;
					opacity: 1;
					transform: scaleY(1)
				}
			}

			@keyframes fadenum {

				/*设置内容由显示变为隐藏*/
				0% {
					opacity: 0;
				}

				100% {
					opacity: 1;
				}
			}
		</style>
	</head>
	<body>
		<input type="file" multiple="multiple" maxsize="50000" onchange="update()" accept="image/gif,image/jpeg,image/png,image/jpg,video/mp4" />
		<div id="imgsArry"></div>
	</body>
	<script type="text/javascript">
		// !function test(){
		//     // 捕获异常，递归次数过多调试工具会抛出异常。
		//     try { !
		//         function cir(i) {
		//             // 当打开调试工具后，抛出异常，setTimeout执行test无参数，此时i == NaN，("" + i / i).length == 3
		//             // debugger设置断点
		//             (1 !== ("" + i / i).length || 0 === i) &&
		//             function() {}.constructor("debugger")(),
		//             cir(++i);
		//         } (0)
		//     } catch(e) {
		//         setTimeout(test, 500)
		//     }
		// }()
		

		const imgs = document.querySelector('input[type=file]'); //获取file
		const imgsArry = document.getElementById('imgsArry');
		const filetype = imgs.getAttribute('datatype'); //获取自定义读取图片类型

		let imgsBlobArry = []; //存放blob数据
		let imgArrylist = []; //存放图片对象
		let Eedom = [];

		function update() {

			const typeFile = imgs.accept || imgs.accept.replace(/\s/g, "").split(",");
			if (parseInt(imgs.getAttribute("maxsize")) < imgs.files.length) {
				console.log("超出了数量");
				console.error('Exceeded number of custom files')
				// return false;
				back;
			}

			for (let i = 0; i < imgs.files.length; i++) { //获取的图片放入数组
				imgArrylist.push(imgs.files[i]);

				if (typeFile.indexOf(imgs.files[i].type) === -1) {
					console.warn('上传文件类型有误');
					continue;
				}

				let reader = new FileReader();

				reader.readAsDataURL(imgs.files[i]);

				reader.onerror = function(e) { //出错
					// console.log(e)
				};

				reader.onloadstart = function(e) { //开始读取
					// console.warn(e)
				};

				reader.onprogress = function(e) {
					parseInt(e.loaded / imgs.files[i].size * 100)
				};

				reader.onload = function(e) {
					imgsBlobArry.push({
						name: imgs.files[i].name,
						fileType: imgs.files[i].type,
						size: conver(imgs.files[i].size),
						url: e.target.result,
						lastModifiedDate: imgs.files[i].lastModifiedDate
					});

					let TheLabel;
					if (String(imgs.files[i].type).includes('image')) {
						TheLabel = new Image;

					} else if (String(imgs.files[i].type).includes('video')) {
						TheLabel = document.createElement('video');

					} else if (String(imgs.files[i].type).includes('audio')) {
						TheLabel = new Audio;

					} else { //其他文件
						TheLabel = document.createElement('div').innerHTML = `<img src="../img/file.jpg" alt="文件" style="width: 10%;">`
					}

					let imgCont = document.createElement('div'); //最外层div
					let close = document.createElement('p'); //最外层div
					let progress = document.createElement('div'); // 显示进度条div
					close.className = 'close';
					close.style = `text-align: end;line-height: 0;cursor: pointer;`;
					close.innerHTML = `X`;

					TheLabel.style = `width:100%;height:100%`;
					TheLabel.src = e.target.result;
					TheLabel.id = "examine";
					imgCont.className = "imgshow imgcontshow";
					imgCont.style = `width: 10%;height: 10%;float: left;`;
					progress.style = `width:100%;height:0.2rem;background:#10affb`;
					imgCont.appendChild(close);
					imgCont.appendChild(TheLabel);
					imgCont.appendChild(progress);
					imgsArry.appendChild(imgCont);
					Eedom.push(TheLabel)
					// postJSON('http://localhost:3692/imges',{city:e.target.result}).then()
					// postJSON('http://localhost:3692/imges',{city:imgsBlobArry}).then()
				}

				function dataURLtoBlob(dataurl) {
					var arr = dataurl.split(','),
						mime = arr[0].match(/:(.*?);/)[1],
						bstr = atob(arr[1]),
						n = bstr.length,
						u8arr = new Uint8Array(n);
					// console.log(arr);
					// console.log(mime);
					// console.log(bstr);
					// console.log(n);
					// console.log(u8arr);

					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					console.log([u8arr])
					return new Blob([u8arr], {
						type: mime
					});
				}

				// let   blobs = window.URL.createObjectURL(imgs.files[i]) //获取blob二进制数据，可用来显示

				// imgsBlobArry.push({
				//     name:imgs.files[i].name,
				//     fileType:imgs.files[i].type,
				//     size:conver(imgs.files[i].size),
				//     uer:blobs,
				//     lastModifiedDate:imgs.files[i].lastModifiedDate
				// });


			}




			// window.URL.revokeObjectURL(blobs) //手动回收
			setTimeout(() => {
				if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
					console.log("超出数量");
					imgs.style.display = 'none';
				} else {
					imgs.style.display = "table";
				}
			}, 50);

			function conver(limit) { //图片大小 mb 换算
				let size = "";
				if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
					size = limit.toFixed(2) + "B";
				} else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
					size = (limit / 1024).toFixed(2) + "KB";
				} else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
					size = (limit / (1024 * 1024)).toFixed(2) + "MB";
				} else { //其他转化成GB
					size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
				}
				let sizestr = size + "";
				let len = sizestr.indexOf("\.");
				let dec = sizestr.substr(len + 1, 2);
				if (dec === "00") { //当小数点后为00时 去掉小数部分
					return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
				}
				return sizestr;
			}



			setTimeout(() => {  //图片压缩

				Eedom.forEach((e, index) => { 
					reduceImg({
						src: e.src,
						index
					})
				})
			}, 100)

		}





		function reduceImg(data) {  //图片压缩方法
			const {
				src,
				index,
				w = 200,
				h = 200
			} = data;
			let img = new Image();
			img.src = src
			setTimeout(() => {
				//图片的原始尺寸
				let originWidth = img.width;
				let originHeight = img.height;
				//最大尺度的尺寸限制默认在 200*200
				let maxWidth = w,
					maxHeight = h;
				//目标尺寸
				console.log(originWidth, originHeight)
				let targetWidth = originWidth,
					targetHeight = originHeight;
				if (originWidth > maxWidth || originHeight > maxHeight) { //如果原始尺寸大于了设定的最大尺寸
					if (originWidth / originHeight > maxWidth / maxHeight) { //图片原本的宽高比例大于了设定的宽高比例
						//大于规定的比例 证明 原始宽度大于高度 -》所以按照高度除以宽度的比例去缩放高度
						targetWidth = maxWidth;
						targetHeight = Math.round(maxWidth * (originHeight / originWidth));
					} else {
						//小于则表明 原始高度大于原始宽度 -》所以按照宽度除以高度的比例去缩放宽度
						targetHeight = maxHeight;
						targetWidth = Math.round(maxHeight * (originWidth / originHeight));
					}
				}
				let canvas = document.createElement('canvas');
				let context = canvas.getContext('2d');
				// canvas对图片进行缩放
				canvas.width = targetWidth;
				canvas.height = targetHeight;
				// 清除画布
				context.clearRect(0, 0, targetWidth, targetHeight);
				// 图片压缩

				let imgys = document.createElement('img');

				imgys.src = src;
				context.drawImage(imgys, 0, 0, targetWidth, targetHeight);
				// canvas转为blob并上传
				console.log(canvas.toDataURL('image/png'))
				// imgsBlobArry[index].url = canvas.toDataURL('image/png')
				postJSON('http://localhost:1088/imges',{city:canvas.toDataURL('image/png')}).then()
				
				canvas.toBlob(function(blob) {
					
					imgsBlobArry[index].url =window.URL.createObjectURL(blob)
					
					console.log(window.URL.createObjectURL(blob))
				}, 'image/png', 0.95);
				
			}, 100)
			// console.log(imgsBlobArry)
			// postJSON('http://localhost:1088/imges',{city:imgsBlobArry}).then()
		}


		// console.log(imgsBlobArry)

		//点击图片查看
		var el = window.document.body; //声明一个变量，默认值为body
		window.document.body.onclick = function(event) {
			if (event.target.id === "") {
				if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
					document.body.removeChild(document.getElementById('showimg'))
				}
			}
			let lookOver = document.getElementById('imgShow');
			if (event.target.tagName === 'IMG' || event.target.tagName === 'VIDEO' || event.target.tagName === 'Audio') {

				let showimg = event.target.tagName === "IMG" ? new Image : event.target.tagName === "VIDEO" ? document.createElement(
					'video') : new Audio;
				showimg.autoplay = true
				showimg.controls = true
				let divshow = document.createElement('div');
				showimg.style =
					`position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);animation: fadenum 2s forwards`;
				showimg.src = event.target.src;
				divshow.id = 'showimg';
				divshow.style = `position: fixed;top: 0px;width: 100%;height: 100%;background: rgba(0,0,0,0.1);text-align:center;`

				divshow.appendChild(showimg)

				if (!lookOver) {
					document.body.appendChild(divshow)
				}

			}

			if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
				document.body.removeChild(document.getElementById('showimg'))
			}


			if (event.target.tagName === 'P') {
				document.querySelectorAll('.close').forEach((tiem, index) => {
					tiem.onclick = function() {
						console.log(this.parentNode);
						document.getElementById('imgsArry').removeChild(this.parentNode);
						imgsBlobArry.splice(index, 1);

						console.log(imgsBlobArry)
					}
				});
				if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
					console.log("超出数量")
					imgs.style.display = 'none';

				} else {
					imgs.style.display = "table";
				}
			}
		};


		function postJSON(url, data) {
			return new Promise((resolve, reject) => {
				var xhr = new XMLHttpRequest()
				xhr.open("POST", url, true)
				xhr.datatype = 'json'
				xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");

				xhr.onreadystatechange = function() {
					if (this.readyState === 4) {
						if (this.status === 200) {
							resolve(JSON.parse(this.responseText), this)
						} else {
							var resJson = {
								code: this.status,
								response: this.response
							}
							reject(resJson, this)
						}
					}
				}

				xhr.send(JSON.stringify(data))
			})
		}



		// postJSON('http://60.10.165.110:8001/fbjd/msg/weather',{city:101090608}).then()
	</script>
</html>
